package com.example.tongyao.system.controller;

import com.example.tongyao.system.entity.SysUser;
import com.example.tongyao.utils.DataResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpStatus;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户登录认证
 *
 * @version 1.0
 * @author tongyao
 * @since 2020-06-13
 */
@RestController
@Api(tags = "系统 - 登录认证")
public class AuthController {

    /**
     * 登录接口
     * @param username
     * @param password
     * @return
     */
    @ApiOperation(
            value = "登录认证",
            notes = "登录认证",
            httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username",value = "账号",required = true),
            @ApiImplicitParam(name = "password",value = "密码",required = true)
    })
    @PostMapping(value = "/login" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult login(String username,String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            SysUser user = (SysUser) subject.getPrincipal();
            if(user.getStatus() != true){
                return DataResult.setResult(HttpStatus.SC_ACCEPTED,"该账户禁止登录！");
            }

            if(user.getSysRole().getRoleStatus() != true){
                return DataResult.setResult(HttpStatus.SC_ACCEPTED,"该账户角色未开放，请联系管理员！");
            }

            if(user.getSysRole().getDelFlag() != true){
                return DataResult.setResult(HttpStatus.SC_ACCEPTED,"该角色已删除！请联系管理员重新分配。");
            }

            //存储sessionId
            user.setSessionId(subject.getSession().getId()+"");
            return DataResult.setResult(user);
        }catch (Exception e) {
            return DataResult.setResult(HttpStatus.SC_ACCEPTED,"账号或密码错误！");
        }
    }

    /**
     * 退出登录
     * @return
     */
    @ApiOperation(value = "退出登录", notes = "退出登录")
    @GetMapping("/logout")
    public DataResult logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        return DataResult.setSuccess(true);
    }
	
}
